<template>
    <div class="boxs">
        <el-card>
            <el-form :model="queryParams" ref="queryForm" :inline="true">
                <el-form-item label="uuid">
                    <el-input v-model="queryParams.uuid" placeholder="uuid" />
                </el-form-item>
                <el-form-item label="排序方式">
                    <el-select v-model="queryParams.orderBy" @change="handleQuery">
                        <el-option v-for="item in orderByList" :key="item.id" :label="item.name"
                            :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="时间范围">
                    <el-date-picker v-model="value1" value-format="yyyy-MM-dd" type="daterange" range-separator="-"
                        :start-placeholder="$t('table.start')" :end-placeholder="$t('table.end')" @change="timeChange">
                    </el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" size="small"
                        @click="handleQuery">{{ $t('table.search') }}</el-button>
                    <el-button icon="el-icon-refresh" size="small"
                        @click="resetQuery">{{ $t('table.reset') }}</el-button>
                </el-form-item>
            </el-form>
            <div class="flex_between">
                <el-button size="mini" type="primary" @click="handleBatchDelete()">config</el-button>
                <div></div>


            </div>
            <el-table border :data="moreArr" style="margin-top: 15px" v-loading="loading">
                <el-table-column label="index" type="index" align="center" width="80" />

                <el-table-column label="uuid" align="center" prop="uuid">
                </el-table-column>
                <el-table-column label="invite_code" align="center" prop="invite_code">
                </el-table-column>
                <el-table-column label="total_invite" align="center" prop="total_invite">
                </el-table-column>
                <el-table-column label="total_free_count" align="center" prop="total_free_count">
                </el-table-column>
                <el-table-column label="used_free_count" align="center" prop="used_free_count">
                </el-table-column>
                <el-table-column label="remaining_free_count" align="center" prop="remaining_free_count">
                </el-table-column>
                <el-table-column label="inviteList" align="center" prop="url">
                    <template slot-scope="scope">
                        <div :style="{
    cursor: scope.row.total_invite == 0 ? 'not-allowed' : 'pointer',
    color: scope.row.total_invite == 0 ? 'gray' : 'blue'
                        }" @click="scope.row.total_invite != 0 && openDialogList(scope.row)">
                            inviteList
                        </div>
                    </template>
                </el-table-column>

                <el-table-column label="created_date" align="center" width="180" prop="created_date">
                </el-table-column>
                <el-table-column label="update_date" align="center" width="180" prop="update_date">
                </el-table-column>

            </el-table>
            <pagination v-show="total > 0" :total="total" :page.sync="queryParams.page" :limit.sync="queryParams.size"
                @pagination="getMore" />
        </el-card>

        <el-dialog :visible.sync="dialogVisible" @close="dialogVisible = false" width="600px">
            <el-form class="demo-form-inline" label-width="170px" :model="configData" :rules="rules" ref="ruleForm">
                <el-form-item label="SKInviteCount" prop="SKInviteCount">
                    <el-input-number v-model="configData.SKInviteCount" :precision="0" :step="1" :min="1"
                        :max="1000"></el-input-number>
                </el-form-item>
                <el-form-item label="SKInviteShareBtnLink" prop="SKInviteShareBtnLink">
                    <el-input v-model="configData.SKInviteShareBtnLink" :placeholder="$t('review.templateType')" />
                </el-form-item>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">{{ $t('review.close') }}</el-button>
                <el-button :loading="addLoading" :type="form.id ? 'warning' : 'primary'" @click="affirm">{{
                    $t('review.confirm')
                }}</el-button>
            </div>
        </el-dialog>
        <el-dialog :visible.sync="dialogVisibleList" @close="handleClose">
            <el-table border :data="inviteList" style="margin-top: 15px" v-loading="loading">
                <el-table-column label="index" type="index" align="center" width="80" />
                <el-table-column label="uuid" align="center" prop="uuid">
                </el-table-column>
                <el-table-column label="invite_code" align="center" prop="invite_code">
                </el-table-column>
                <el-table-column label="total_invite" align="center" prop="total_invite">
                </el-table-column>
                <el-table-column label="total_free_count" align="center" prop="total_free_count">
                </el-table-column>
                <el-table-column label="used_free_count" align="center" prop="used_free_count">
                </el-table-column>
                <el-table-column label="remaining_free_count" align="center" prop="remaining_free_count">
                </el-table-column>
                <el-table-column label="created_date" align="center" width="180" prop="created_date">
                </el-table-column>
            </el-table>
            <pagination v-show="inviteTotal > 0" :total="inviteTotal" :page.sync="query.page" :limit.sync="query.size"
                @pagination="getMore1" />
        </el-dialog>
    </div>
</template>
<script>
import { getImageList, deleteHandel, batchDeleteHandel, getProductInfoList, deleteHandelProductInfo, batchDeleteHandelProductInfo, getBeautyUserList, getInviteConfig, updateInviteConfig, getBeautyInviteList } from "@/api/beauty";

import pk from "@/utils/pk";
export default {
    name: "RequestRecord",
    data() {
        return {
            environmentList: [
                {
                    id: 'com.seamobitech.BeautyAI',
                    name: 'Production'
                },
                {
                    id: 'com.tcdemotc.testApp',
                    name: 'Testing'
                },
            ],
            orderByList: [
                {
                    id: 'update_date',
                    name: 'update_date',
                },
                {
                    id: 'total_invite',
                    name: 'total_invite',
                },
                
            ],
            currentImageUrl: '',
            queryParams: {
                page: 1,
                size: 10,
                dateRange: {
                    start: "",
                    end: "",
                },
                type: "",
                uuid: '',
                orderBy:'update_date'
            },
            stateList: [
                {
                    id: 'face',
                    name: 'face'
                },
                {
                    id: 'makeup',
                    name: 'makeup'
                },
                {
                    id: 'product',
                    name: 'product'
                },
            ],
            productIdList: [
                {
                    name: 'subs.week',
                    id: 'subs.week'
                },
                {
                    name: 'subs.week.premium',
                    id: 'subs.week.premium'
                },
                {
                    name: 'subs.month',
                    id: 'subs.month'
                },
                {
                    name: 'subs.month.premium',
                    id: 'subs.month.premium'
                },
                {
                    name: 'subs.year',
                    id: 'subs.year'
                },
                {
                    name: 'subs.year.premium',
                    id: 'subs.year.premium'
                },
                {
                    name: 'pro.lifetime',
                    id: 'pro.lifetime'
                },
                {
                    name: 'NA',
                    id: 'NA'
                },
            ],
            total: 0,
            loading: false,
            addLoading: false,
            moreArr: [],
            dialogVisible: false,
            form: {
                description: "",
                file: "",
            },
            search: "",
            rules: {
                SKInviteCount: [
                    { required: true, message: "Please enter SKInviteCount", trigger: "blur" },
                ],
                SKInviteShareBtnLink: [
                    { required: true, message: "Please enter SKInviteShareBtnLink", trigger: "blur" },
                ],
            },
            value1: "",
            dialogVisibleList: false,
            configData: {},
            query: {
                page: 1,
                size: 10,
                uuid:''
            },
            inviteList: [],
            inviteTotal:0
        };
    },
    watch: {
        'form.state'(newVal) {
            if (newVal === '2') {
                this.form.productId = 'NA'; // Set to NA ID
            }
        }
    },
    created() {
        this.getMore();
        // this.init()
    },
    methods: {
        async openDialogList(row) {
            this.query.uuid=row.uuid
            const { data, total } = await getBeautyInviteList(this.query)
            this.inviteList=data
            this.inviteTotal = total
            this.dialogVisibleList=true
        },
        async getMore1() {
            this.loading = true;
            let { data, total } = await getBeautyInviteList(this.query);
            this.loading = false;
            this.inviteList = data
            this.inviteTotal = total
        },

        copyOrder() {
            const input = document.createElement('textarea');
            input.value = this.form.orderId;
            document.body.appendChild(input);
            input.select();
            try {
                document.execCommand('copy');
                this.$message({
                    message: 'Text copied to clipboard!',
                    type: 'success'
                });
            } catch (err) {
                this.$message({
                    message: 'Failed to copy text.',
                    type: 'error'
                });
            }
            document.body.removeChild(input);

        },
        copyOrder2(data1) {
            const input = document.createElement('textarea');
            input.value = data1;
            document.body.appendChild(input);
            input.select();
            try {
                document.execCommand('copy');
                this.$message({
                    message: 'Text copied to clipboard!',
                    type: 'success'
                });
            } catch (err) {
                this.$message({
                    message: 'Failed to copy text.',
                    type: 'error'
                });
            }
            document.body.removeChild(input);
        },
        copyOrder1(data1) {
            let data = this.extractErrorFromJsonString(data1)
            const input = document.createElement('textarea');
            input.value = data;
            document.body.appendChild(input);
            input.select();
            try {
                document.execCommand('copy');
                this.$message({
                    message: 'Text copied to clipboard!',
                    type: 'success'
                });
            } catch (err) {
                this.$message({
                    message: 'Failed to copy text.',
                    type: 'error'
                });
            }
            document.body.removeChild(input);
        },
        extractErrorFromJsonString(jsonString) {
            if (JSON.parse(jsonString).content && JSON.parse(jsonString).content.includes('```json')) {
                if (JSON.parse(jsonString).content.charAt(0) === '`') {
                    if (JSON.parse(JSON.parse(jsonString).content.replace(/```json|```/g, '').trim()).error) {
                        return JSON.parse(JSON.parse(jsonString).content.replace(/```json|```/g, '').trim()).error
                    } else {
                        return jsonString
                    }
                } else {
                    return JSON.parse(jsonString).content

                }

            } else {

                return JSON.parse(jsonString).refusal || JSON.parse(jsonString).content
            }
        },
        copyEmail() {
            const input = document.createElement('textarea');
            input.value = this.form.email;
            document.body.appendChild(input);
            input.select();
            try {
                document.execCommand('copy');
                this.$message({
                    message: 'Text copied to clipboard!',
                    type: 'success'
                });
            } catch (err) {
                this.$message({
                    message: 'Failed to copy text.',
                    type: 'error'
                });
            }
            document.body.removeChild(input);

        },
        copyEmail1(data) {
            const input = document.createElement('textarea');
            input.value = data;
            document.body.appendChild(input);
            input.select();
            try {
                document.execCommand('copy');
                this.$message({
                    message: 'Text copied to clipboard!',
                    type: 'success'
                });
            } catch (err) {
                this.$message({
                    message: 'Failed to copy text.',
                    type: 'error'
                });
            }
            document.body.removeChild(input);
        },
        uploadHandel(e) {
            this.form.file = e.file;
        },
        remeveFile() {
            this.form.file = "";
        },
        timeChange() {
            this.queryParams.dateRange.start = this.value1[0];
            this.queryParams.dateRange.end = this.value1[1];
            this.handleQuery();
        },
        getKeyByValue(object, value) {
            return Object.keys(object).find((key) => object[key] === value);
        },
        async getMore() {
            this.loading = true;
            let { data, total } = await getBeautyUserList(this.queryParams);
            this.loading = false;
            this.moreArr = data;
            this.total = total;
        },

        handleQuery() {
            this.queryParams.page = 1;
            this.getMore();
        },
        async affirm() {
            this.$refs["ruleForm"].validate(async (valid) => {
                if (!valid) return;
                try {
                    this.addLoading = true;
                    await updateInviteConfig(this.configData);
                    this.addLoading = false;
                    this.$message.success("操作成功");
                    this.getMore();
                    this.dialogVisible = false;
                } catch (e) {
                    this.addLoading = false;
                }
            });
        },
        openDialog(url) {
            this.currentImageUrl = url;
            this.dialogVisible = true;
        },
        handleEdit(i, row) {
            if (row.images) {
                row.imagesList = row.images.split('|')
            }
            if (row.state == '0') {
                row.state = '1'
            }
            this.form = Object.assign({}, row);
            if (this.$refs.upload) {
                this.$refs.upload.clearFiles(); // 清除文件列表
            }
            this.dialogVisible = true;
        },
        handleDelete(index, row) {
            this.$confirm(this.$t('review.deleteText1'), this.$t('review.deleteText2'), {
                confirmButtonText: this.$t('review.confirm'),
                cancelButtonText: this.$t('review.close'),
                type: "error",
            }).then(async () => {
                this.addLoading = true;
                this.elloading = this.$loading({
                    lock: true,
                    text: 'Loading',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.7)'
                });
                try {
                    await deleteHandelProductInfo({ id: row.id, image: row.image });
                    this.getMore();
                    this.$message({
                        message: "success!",
                        type: "success",
                    });
                } catch (error) {
                    // 在这里可以添加错误处理逻辑
                    console.error("Error during deletion:", error);
                    this.$message({
                        message: "Failed to delete!",
                        type: "error",
                    });
                } finally {
                    this.addLoading = false;
                    this.elloading.close();

                }
            })
        },
        async handleBatchDelete() {
            let { data } = await getInviteConfig();
            this.configData = data
            this.dialogVisible = true
        },
        resetQuery() {
            this.queryParams.orderBy = 'update_date';
            this.queryParams.uuid = null;
            this.queryParams.type = null;
            this.queryParams.package_name = null;
            this.queryParams.dateRange.start = null;
            this.queryParams.dateRange.end = null;
            this.queryParams.page = 1;
            this.value1 = "";
            this.getMore();
        },
    },
};
</script>
<style lang="scss" scoped>
.boxs {
    padding: 20px;
}

::v-deep.el-input.is-disabled .el-input__inner {
    color: #333 !important;
}

::v-deep.el-textarea.is-disabled .el-textarea__inner {
    color: #333 !important;
}

::v-deep .el-upload {
    width: 100% !important;
}

::v-deep .el-upload-dragger {
    width: 100% !important;
}

.product-item {
    border: 1px solid #ebeef5;
    border-radius: 4px;
    padding: 15px;
    margin-bottom: 20px;
    background-color: #fff;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.product-image {
    width: 100%;
    height: auto;
    border-radius: 4px;
}

.product-brand,
.product-name {
    font-size: 14px;
    color: #606266;
}
</style>